# apps/orders/signals.py
from django.db.models.signals import post_save
from django.dispatch import receiver, Signal
from .models import DjChefOrder, Order, ORDER_TO_CHEF_STATUS, CHEF_TO_ORDER_STATUS

# 定义信号（使用清晰的命名）
order_status_changed = Signal()  # 订单状态变更信号
chef_order_status_changed = Signal()  # 厨师订单状态变更信号

# 原接收器函数与信号同名，导致冲突，重命名接收器
@receiver(post_save, sender=Order)
def handle_order_post_save(sender, instance, **kwargs):  # 重命名函数
    if 'status' in instance.get_deferred_fields():
        # 发送状态变更通知
        from .tasks import send_order_notification
        send_order_notification.delay(instance.id)

@receiver(post_save, sender=Order)
def sync_order_to_chef_order(sender, instance,** kwargs):
    """用户订单状态变更时，同步到厨师订单"""
    try:
        chef_order = instance.chef_order
    except DjChefOrder.DoesNotExist:
        return

    target_status = ORDER_TO_CHEF_STATUS.get(instance.status)
    if target_status and chef_order.status != target_status:
        chef_order.change_status(
            to_status=target_status,
            note=f"同步自用户订单状态变更：{instance.get_status_display()}"
        )

@receiver(post_save, sender=DjChefOrder)
def sync_chef_order_to_order(sender, instance, **kwargs):
    """厨师订单状态变更时，同步到用户订单"""
    order = instance.original_order
    target_status = CHEF_TO_ORDER_STATUS.get(instance.status)
    if target_status and order.status != target_status:
        order.change_status(
            to_status=target_status,
            note=f"同步自厨师订单状态变更：{instance.get_status_display()}"
        )